package epoch.db.cmd;

import java.util.concurrent.ConcurrentLinkedQueue;

import epoch.game.core.thread.ServerThread;

/**
 * 数据库操作对象池，非线程安全
 * 
 * @author will
 * @date 2016年8月11日 下午7:24:07
 */
public class DBCommandPool {

	private ConcurrentLinkedQueue<DBCommand> cmds = new ConcurrentLinkedQueue<DBCommand>();
	private int maxSize;

	public DBCommandPool(ServerThread thread, int poolSize) {
		init(thread, poolSize);
	}
	
	public DBCommandPool(int poolSize) {
		init(new ServerThread(), poolSize);
	}
	
	private void init(ServerThread thread, int poolSize){
		this.maxSize = poolSize;
	}
	
	public void release(DBCommand dbCmd){
		dbCmd.destroy();
		if (cmds.size() < maxSize) {
			cmds.add(dbCmd);
		}
	}
	
	@SuppressWarnings("unchecked")
	public <T extends DBCommand> T get(DBCommandType type){
		if(cmds.isEmpty()){
			switch(type){
				case EntityCmd:
					return (T) new EntityCommand();
				case SQLCmd:
					return (T) new SqlCommand();
			}
			return null;
		}else{
			return (T)cmds.poll();
		}
	}
}
